//
//  OAuthViewController.swift
//  MyBlog
//
//  Created by lvtienan on 15/7/31.
//  Copyright © 2015年 ltn. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 用户输入用户名密码的界面
class OAuthViewController: UIViewController, UIWebViewDelegate {

    // MARK: - 搭建界面
    private var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    // 销毁登录界面 这个方法不能使用private .因为是谁 modal 谁 dismiss
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 请求登录界面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedNetworkTools.oauthUrl()))
    }
    
    //UIWebViewDelegate
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 如果request中包含回调地址,需要判断参数 code,否则就继续加载
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix(NetworkTools.sharedNetworkTools.redirectUri) {
            return true
        }
        
        // print(request)
        // URL: http://www.baidu.com/?code=d9eb2d842dcfa8f59a592afa4739a764

        if let query = request.URL?.query where query.hasPrefix("code=") {
            
          let code =  query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            print("获取授权码"+code)
            loadAccessToken(code)
            
        }else {
            close()
        }

        return false
    }
    
    private func loadAccessToken(code:String) {
        NetworkTools.sharedNetworkTools.loadAccessToken(code) { (result, error) -> () in
            
            // 如果返回错误或者 result 没有值
            if error != nil || result == nil {
                
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                self.netError()
                return
            }
            
            /// 成功拿到 token
            // 字典转模型
            UserAccount(dict: result!).loaduserInfo({ (error) -> () in
                if error != nil {
                    self.netError()
                    return
                }
                
                // 发送通知,切换控制器
            NSNotificationCenter.defaultCenter().postNotificationName(HMRootViewControllerSwitchNotification, object: false)
                // 关闭控制器
                self.close()
            })
            
        }
    }
    
    // 网络错误处理
    private func netError() {
        // 延时一段时间,关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64 (1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
            self.close()
        })
    }
    
}
